import { defineStore } from 'pinia';
import { ref } from 'vue';
import { GetStoreByUserLocation } from '@/api/api.js';
import { useAppointmentStore } from '@/store/appointment';
import { useUserStore } from '@/store/user';

export const useShopStore = defineStore('shop', () => {
  const latitude = ref(0);
  const longitude = ref(0);
  const nearby = ref([]);
  const askLocationPermission = ref(true);

  function getNearbyShop() {
    uni.getSetting({
      success: (res) => {
        console.log('getSetting', res);
        if (res.authSetting['scope.userLocation']) {
          uni.getLocation({
            type: 'gcj02',
            success: (result) => {
              console.log('getLocation', result);
              latitude.value = result.latitude;
              longitude.value = result.longitude;
              uni.showLoading({
                title: '加载中...',
              });
              GetStoreByUserLocation(result.longitude, result.latitude)
                .then((data) => {
                  nearby.value = data || [];
                })
                .finally(() => {
                  uni.hideLoading();
                });
              const userStore = useUserStore();
              if (userStore.isLogin) {
                const appointmentStore = useAppointmentStore();
                appointmentStore.getHistoryAppointments();
              }
            },
            fail: (error) => {
              console.error('getLocation', error);
              uni.showToast({
                title: '定位失败',
                icon: 'none',
              });
            },
          });
        } else {
          latitude.value = 0;
          longitude.value = 0;
          uni.showLoading({
            title: '加载中...',
          });
          GetStoreByUserLocation(longitude.value, latitude.value)
            .then((data) => {
              nearby.value = data || [];
            })
            .finally(() => {
              uni.hideLoading();
            });
          const userStore = useUserStore();
          if (userStore.isLogin) {
            const appointmentStore = useAppointmentStore();
            appointmentStore.getHistoryAppointments();
          }
          // uni.showToast({
          //   title: "定位失败",
          //   icon: "none",
          // });
          if (askLocationPermission.value) {
            askLocationPermission.value = false;
            uni.showModal({
              title: '温馨提示',
              content: '您已拒绝授权，请点击确认打开设置界面',
              showCancel: true,
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting();
                }
              },
            });
          }
        }
      },
    });
  }

  return {
    latitude,
    longitude,
    nearby,
    getNearbyShop,
    askLocationPermission,
  };
});
